package com.personal.dao.sqlgenerator;

import java.util.ArrayList;
import java.util.List;

import com.personal.dao.bean.BaseModel;
import com.personal.dao.configuration.Configuration;
import com.personal.dao.exception.NoPrimaryKeyException;
import com.personal.dao.metadata.DataBaseFieldMetadata;
import com.personal.dao.metadata.DataBasePrimaryKeyMetadata;
import com.personal.dao.metadata.DataBaseTableMetadata;
import com.personal.dao.reflection.MetaObject;
import com.personal.dao.sql.BaseSql;
import com.personal.dao.sql.Sql;

/**
 * 通过条件查询个数
 * @author cuibo
 *
 */
public class InsertSelective<T extends BaseModel> extends BaseSqlGenerator<T>
{

    public InsertSelective(T value, DataBaseTableMetadata<T> metadata)
    {
        super(value, metadata);
    }

    @Override
    public Sql generate()
    {
    	MetaObject metaObject = Configuration.getInstance().newMetaObject(this.value);
    	// 校验
    	SqlValidator.validate(metadata, this.value, metaObject);
        StringBuilder before = new StringBuilder("insert into ").append(metadata.getTableName()).append(" (");
        StringBuilder after = new StringBuilder();
        List<Object> list = new ArrayList<Object>();
        
        DataBasePrimaryKeyMetadata primaryKey = metadata.getPrimaryKey();
        if (primaryKey != null)
        {
            before.append(primaryKey.getColumnName()).append(",");
            after.append("?,");
            Object value = metaObject.getValue(primaryKey.getFieldName());
        	if (value == null)
			{
        		// 考虑自动生成
            	if (primaryKey.getGenerator() != null)
    			{
            		value = primaryKey.getGenerator().generatorPrimaryKey();
            		metaObject.setValue(primaryKey.getFieldName(), value);
    			}
            	if (value == null)
    			{
            		throw new NoPrimaryKeyException(this.value + "的主键不能为空！");
    			}
			}
            list.add(value);
        }
        for (DataBaseFieldMetadata field : metadata.getFields())
        {
            Object value = metaObject.getValue(field.getFieldName());
            if (value != null)
            {
                before.append(field.getColumnName()).append(",");
                after.append("?,");
                list.add(value);
            }
        }
        before.deleteCharAt(before.length() - 1).append(")").append(" values (");
        before.append(after.deleteCharAt(after.length() - 1)).append(")");
        return new BaseSql(before.toString(), list);
    }

}
